/*
 * Copyright 2010 Thedwick, LLC

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.

 */
package com.thedwick.jdbcGrabber.util;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Properties;

public class ClassUtil {
	/**
	 * Reads a properties file and creates a new instance of a class from an entry in it
	 * 
	 * @param propertyKey
	 * @param config
	 * @throws IllegalArgumentException for any of the variety of ways it might fail to create
	 * 			an instance of that class
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static Object createInstance(String propertyKey, Properties config, Object... constructorArgs){
		String className = config.getProperty(propertyKey);
		if (className == null){
			throw new IllegalArgumentException("missing " + propertyKey + " in properties file");
		}
		try {
			Class clazz = Class.forName(className);
			ArrayList<Class> argClasses = new ArrayList<Class>(constructorArgs.length);
			for (Object obj : constructorArgs){
				argClasses.add(obj.getClass());
			}
			Class[] theClasses = new Class[argClasses.size()];
			Constructor<Object> constructor = clazz.getConstructor(argClasses.toArray(theClasses));
			Object rv = constructor.newInstance(constructorArgs);
			return rv;
		} catch (ClassNotFoundException e) {
			throw new IllegalArgumentException("failed to create class: " + className, e);
		} catch (SecurityException e) {
			throw new IllegalArgumentException("failed to create class: " + className, e);
		} catch (NoSuchMethodException e) {
			throw new IllegalArgumentException("failed to create class: " + className, e);
		} catch (IllegalArgumentException e) {
			throw new IllegalArgumentException("failed to create class: " + className, e);
		} catch (InstantiationException e) {
			throw new IllegalArgumentException("failed to create class: " + className, e);
		} catch (IllegalAccessException e) {
			throw new IllegalArgumentException("failed to create class: " + className, e);
		} catch (InvocationTargetException e) {
			throw new IllegalArgumentException("failed to create class: " + className, e);
		}	
	}
}
